package Controller;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import message.MessageSend;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import DAO.BoxDao;
import DAO.BranchDao;
import DAO.DealDao;
import DAO.ExpenseDao;
import DAO.ExpressDao;
import DAO.GoodsDao;
import DAO.MessageResponseDao;
import DAO.ParcelDao;
import POJO.Courier;
import POJO.Deal;
import POJO.Express;
import POJO.MessageResponse;
import POJO.Parcel;
import POJO.Terminal;
import Thread.AnJieRequestThread;
import Utils.GenerateRandNumHelper;
import Utils.StringDealHelper;

@Controller
@RequestMapping(value = "courier")
public class CourierController {
	static Logger logger = Logger.getLogger(CourierController.class);
	@Autowired
	ParcelDao parcelDao;
	@Autowired
	BoxDao boxDao;
	@Autowired
	MessageResponseDao messageResponseDao;
	@Autowired
	BranchDao branchDao;
	@Autowired
	ExpressDao expressDao;
	@Autowired
	DealDao dealDao;
	@Autowired
	GoodsDao goodsDao;
	@Autowired
	ExpenseDao expenseDao;

	final Object lock = new Object();

	@RequestMapping("/spareBoxes")
	@ResponseBody
	public Map<String, String> spareBoxes() {

		HashMap<String, String> response = new HashMap<String, String>();
		response.put("result", "0");
		return response;
	}

	@RequestMapping("/saveParcel")
	@ResponseBody
	public synchronized Map<String, Object> saveParcel(
			@RequestParam("parcelNum") String parcelNum,
			@RequestParam("phoneNum") String phoneNum,
			@RequestParam(value = "saveRemark", defaultValue = "-1") String saveRemark,
			@RequestParam(value = "doorStatus", defaultValue = "-1") String doorStatus,
			@RequestParam(value = "goodsStatus", defaultValue = "-1") String goodsStatus,
			@RequestParam("boxSeq") String boxSeq, HttpSession session,
			HttpServletRequest request) {
		Terminal terminal = (Terminal) session.getAttribute("terminal");
		Courier courier = (Courier) session.getAttribute("courier");
		Express express = expressDao.getExpressById(courier.getExpressId());

		HashMap<String, Object> response = new HashMap<String, Object>();
			Parcel parcel = new Parcel();
			parcel.setParcelNum(parcelNum);
			parcel.setPhoneNum(phoneNum);
			parcel.setBoxSeq(boxSeq);
				boolean boxAvailable0 = boxDao.isBoxAvailable(terminal, Integer.parseInt(boxSeq));
				boolean boxAvailable6 = boxDao.queryBoxStatus(terminal, Integer.parseInt(boxSeq))==6;
				Parcel latestParcel = parcelDao.latestParcel(terminal.getTerminalID(),Integer.parseInt(boxSeq));
				if (latestParcel!=null&&latestParcel.getStatus() == 0&&boxAvailable0) {
					// 箱格空闲但是包裹未取
					boxDao.updateBoxStatus(terminal.getTerminalID(),
							Integer.parseInt(boxSeq), 1,null);
					response.put("result", "4");
					response.put("errMsg", "该箱格已被占用（设为占用）");
				} else {
					Parcel p = parcelDao.isItSameParcel(terminal, parcel);
					if (p == null&&(boxAvailable0||boxAvailable6)) {
						boolean dealRessult = false;
						if (express.getStatus() != 1
								&& express.getPayWay() != 2) {
							dealRessult = express.deal();
						}
						if (!dealRessult && express.getPayWay() == 0) {
							response.put("result", "2");
							response.put("errMsg", "owning fee");
							response.put("expressName", express.getName());
						} else {
							String checkCode = parcelDao
									.isExistParcelByPhoneNum(terminal,
											parcel.getPhoneNum());

							if (checkCode != null && !checkCode.equals("")) {
								parcel.setCheckCode(checkCode);
							} else {
								do {
									checkCode = GenerateRandNumHelper
											.generate(6);
								} while (parcelDao.isExistParcelByCheckCode(
										terminal, checkCode) != null);
								parcel.setCheckCode(checkCode);
								request.getServletContext().setAttribute(
										terminal.getTerminalID()
												+ parcel.getCheckCode(),
										parcel.getPhoneNum());
							}
							int resultOfInMsgRp = 0;
							try {
								// boolean
								// saveResult=boxDao.boxToggleAvailable(terminal,
								// boxSeq, 1)&&//更新箱格状态
								// parcelDao.checkBoxEmpty(Integer.parseInt(parcel.getBoxSeq()),terminal.getTerminalID());
								int packageID = parcelDao.save(parcel,terminal, courier);
								if (boxDao.boxToggleAvailable(terminal, boxSeq,1) && packageID != 0) {
//									parcel = parcelDao.getParcelbyId(packageID);
									parcel.setId(packageID);
									parcel.setSaveTime(new Timestamp(new Date().getTime()));
									boxDao.setBoxParcel(terminal.getTerminalID(),Integer.parseInt(boxSeq),parcel.getId());
									String msgTemplate = branchDao.getMsgTemplate(terminal.getBranchID());
									MessageSend messageSend = new MessageSend(parcel, terminal, courier,express,msgTemplate);
									MessageResponse messageResponse = messageSend.send();
									resultOfInMsgRp = messageResponseDao.InsertMessageResponse(messageResponse);
									if(!phoneNum.equals(parcel.getPhoneNum())){
										logger.info("存件发送短信（参数和包裹不对应）------"+"返回ID="+packageID+"&包裹ID="+parcel.getId()+"&单号="+parcel.getParcelNum()+"&手机号="+parcel.getPhoneNum()+"&发送内容="+messageResponse.getContent()+"&短信平台="+terminal.getSmsPlatform());
									}
								} else {
									response.put("result", "1");
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
							if (express.getPayWay() != 2) {
								Date date = new Date();
								String logSerialNum = "YBSP" + date.getTime()/ 1000+ GenerateRandNumHelper.generate(3);
								String logComment = express.getName()+ "快递网点快递员,在"+ terminal.getBranch_Short_Addr()+ "设备网点 " + terminal.getTerminal_name()
										+ "号机 ,存入单号为" + parcel.getParcelNum()+ "包裹";
								Deal deal = new Deal();
								deal.setBalance(express.getBalance());
								deal.setCost(0 - express.getCost());
								deal.setExpressId(express.getId());
								deal.setParcelId(parcel.getId());
								deal.setBranchId(terminal.getBranchID());
								deal.setSerialNum(logSerialNum);
								deal.setUserId(courier.getCourierID());
								deal.setComment(logComment);
								dealDao.save(deal);
							}

							if (resultOfInMsgRp == 1) {
								if((terminal.getUpload()==1&&(courier.getCourier_company().contains("韵达")||courier.getCourier_company().contains("汇通")))||terminal.getAgentID()==29||terminal.getAgentParentID()==29){
									AnJieRequestThread rnt = new AnJieRequestThread();
									rnt.setUrl("http://42.121.192.78:8086/ourangel-box-rpc/terminalSystem/createPackage.html");
									rnt.setSign("c8db7d0e24e9a4ac3e42ec9c06ddc5f7");
									rnt.setDeviceSeq(StringDealHelper.getDeviceSeq("YB", "0", String.valueOf(terminal.getTerminalID()), 12));
									rnt.setParcelId(String.valueOf(parcel.getId()));
									rnt.setSaveTime(parcel.getSaveTime().toString());
									rnt.setParcelNum(parcel.getParcelNum());
									rnt.setUserMobileNum(parcel.getPhoneNum());
									rnt.setBoxNum(Integer.parseInt(parcel.getBoxSeq()));
									rnt.setExpressBranchId(String.valueOf(courier.getExpressId()));
									rnt.setCourierId(String.valueOf(courier.getCourierID()));
									rnt.setMobileNum(courier.getPhoneNum());
									Thread thread = new Thread(rnt);
									thread.start();
								}
								if(!"-1".equals(doorStatus)){
									if("0".equals(saveRemark)){
										if("0".equals(doorStatus)&&"1".equals(goodsStatus)){
											int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
											boxDao.saveAbnormalBoxLog(parcel, logID, "门关上， 无物状态。", "物品模块故障或物品太小未检测到。");
										}
										if("0".equals(doorStatus)&&"2".equals(goodsStatus)){
											int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
											boxDao.saveAbnormalBoxLog(parcel, logID, "门关上， 未知状态。", "物品模块故障或物品太小未检测到。");
										}
									}
									if("1".equals(saveRemark)){
										if("0".equals(doorStatus)){
											if("1".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门关上， 无物状态。", "物品模块故障或物品太小未检测到。");
											}
											if("2".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门关上， 未知状态。", "物品模块故障或物品太小未检测到。");
											}
										}
										if("1".equals(doorStatus)){
											if("0".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门未关上，有物状态。", "门检测模块故障或用户门未关入。");
											}
											if("1".equals(goodsStatus)){
												parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
											}
											if("2".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门未关上，未知状态。", "门检测模块故障或用户门未关入。");
											}
										}
									}
									if("2".equals(saveRemark)){
										if("0".equals(doorStatus)){
											if("1".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门关上， 无物状态。", "物品模块故障或物品太小未检测到。");
											}
											if("2".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门关上， 未知状态。", "物品模块故障或物品太小未检测到。");
											}
										}
										if("1".equals(doorStatus)){
											if("0".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门未关上，有物状态。", "门检测模块故障或用户门未关入。");
											}
											if("1".equals(goodsStatus)){
												parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
											}
											if("2".equals(goodsStatus)){
												int logID = parcelDao.saveAbnormalParcelLog(parcel, doorStatus, goodsStatus);
												boxDao.saveAbnormalBoxLog(parcel, logID, "门未关上，未知状态。", "门检测模块故障或用户门未关入。");
											}
										}
									}
								}
								response.put("result", "0");
								response.put("payBalance", express.getBalance());
								response.put("payAlarm", express.getPayAlarm());
								response.put("openCode", checkCode);
								response.put("rfidNum", courier.getRFID());
								response.put("companyName",
										courier.getCourier_company());
							} else {
								response.put("result", "1");
								response.put("errMsg", "sms sending failed");
							}
						}// express.getPayAlarm()!=2

						if (express.getPayAlarm() == 2
								&& express.getPayWay() == 0) {
							express.setStatus(1);
							expressDao.updateState(express);
						}
						if (express.getPayWay() != 2)
							expressDao.updateBalance(express);

					} else {
						if (p!=null&&!boxAvailable0&&p.getBoxSeq().equals(boxSeq)) {
							response.put("result", "0");
							response.put("payBalance", express.getBalance());
							response.put("payAlarm", express.getPayAlarm());
							response.put("openCode", p.getCheckCode());
							response.put("rfidNum", courier.getRFID());
							response.put("companyName",
									courier.getCourier_company());
						} else {
							response.put("result", "3");
							response.put("errMsg", "相同单号及手机号码已经存入过数据库，请勿重新存件。");
						}
						// response.put("errMsg",
						// "same parcelid and tel exist!");
					}
				}
//			else {
//				response.put("result", "4");
//				response.put("errMsg", "该箱号不存在或占用或未处于存件锁定");
//			}
		return response;
	}

	/**
	 * funcID=0023 取消存件功能
	 * 
	 * @param parcelNum
	 * @param phoneNum
	 * @param boxSeq
	 * @param session
	 * @return
	 */
	@RequestMapping("/cancelParcel")
	@ResponseBody
	public synchronized Map<String, String> cancelParcel(
			@RequestParam("parcelNum") String parcelNum,
			@RequestParam("phoneNum") String phoneNum,
			@RequestParam("newBoxSeq") String newBoxSeq, HttpSession session) {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) session.getAttribute("terminal");
		Courier courier = (Courier) session.getAttribute("courier");
		Express express = expressDao.getExpressById(courier.getExpressId());

		Parcel parcel = parcelDao.queryParcel(terminal.getTerminalID(),parcelNum,phoneNum,0);
		if (boxDao.isBoxAvailable(terminal, Integer.parseInt(newBoxSeq))) {
			// 修改柜子状态为可用
			if (parcel==null) {
				response.put("result", "1");
				return response;
			}
			String oldBoxSeq = parcel.getBoxSeq();
			boolean oldBoxResult = boxDao.boxToggleAvailable(terminal,
					oldBoxSeq, 0,0,0);
			boolean newBoxResult = boxDao.boxToggleAvailable(terminal,
					newBoxSeq, 1,0,parcel.getId());
			parcel.setBoxSeq(newBoxSeq);
			boolean parcelResult = parcelDao.updateParcelCancelStatement(
					terminal, parcel);
			// 发送短信给用户
			parcelDao.saveParcelLog(parcel, "【快递员换箱】从"+oldBoxSeq+"号箱换到"+newBoxSeq+"号箱", courier,"箱格太小或未打开。");
			String msgTemplate = branchDao.getMsgTemplate(terminal
					.getBranchID());
			MessageSend messageSend = new MessageSend(parcel, terminal,
					courier,express, msgTemplate + "(以本条短信为准)");
			MessageResponse messageResponse = messageSend.send();
			int resultOfInMsgRp = messageResponseDao
					.InsertMessageResponse(messageResponse);
			if(!phoneNum.equals(parcel.getPhoneNum())){
				logger.info("换箱发送短信（参数和包裹不对应）------包裹ID="+parcel.getId()+"&单号="+parcel.getParcelNum()+"&参数手机号="+phoneNum+"&包裹手机号="+parcel.getPhoneNum()+"&发送内容="+messageResponse.getContent()+"&短信平台="+terminal.getSmsPlatform());
			}
			if (oldBoxResult && newBoxResult && parcelResult
					&& (resultOfInMsgRp == 1)) {
				if((terminal.getUpload()==1&&(parcel.getBelong().contains("韵达")||parcel.getBelong().contains("汇通")))||terminal.getAgentID()==29||terminal.getAgentParentID()==29){
					AnJieRequestThread rnt = new AnJieRequestThread();
					rnt.setUrl("http://42.121.192.78:8086/ourangel-box-rpc/terminalSystem/updatePackage.html");
					rnt.setSign("c8db7d0e24e9a4ac3e42ec9c06ddc5f7");
					rnt.setParcelId(String.valueOf(parcel.getId()));
					rnt.setParcelNum(parcel.getParcelNum());
					rnt.setBoxNum(Integer.parseInt(parcel.getBoxSeq()));
					rnt.setParcelStatus(parcel.getStatus());
					rnt.setGetTime("");
					Thread thread = new Thread(rnt);
					thread.start();
				}
				response.put("result", "0");
			} else {
				response.put("result", "1");
			}
		} else {
			response.put("result", "1");
			response.put("errMsg", "新箱格已占用或不存在");
		}
		return response;
	}

	@RequestMapping("cancelCertainParcel")
	@ResponseBody
	public synchronized Map<String, String> cancelCertainParcel(
			@RequestParam("parcelNum") String parcelNum,
			@RequestParam("phoneNum") String phoneNum, HttpSession session) {
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal = (Terminal) session.getAttribute("terminal");
		Courier courier = (Courier) session.getAttribute("courier");
		Parcel parcel = new Parcel();
		parcel.setTerminalId(terminal.getTerminalID());
		parcel.setParcelNum(parcelNum);
		parcel.setPhoneNum(phoneNum);
		int boxSeq = parcelDao.getCertainPackageBoxSeq(terminal, parcel);

		if ((boxSeq != -1)
				&& boxDao.boxToggleAvailable(terminal, String.valueOf(boxSeq),
						0,0,0)) {
			parcelDao.cancelCertainParcel(parcel);
			parcel = parcelDao.queryParcel(terminal.getTerminalID(),parcelNum,phoneNum,5);
			parcelDao.saveParcelLog(parcel, "【快递员换箱】快递员输错手机号码", courier,"用户手机号码输入错误，本条记录注销");
			if((terminal.getUpload()==1&&(parcel.getBelong().contains("韵达")||parcel.getBelong().contains("汇通")))||terminal.getAgentID()==29||terminal.getAgentParentID()==29){
				AnJieRequestThread rnt = new AnJieRequestThread();
				rnt.setUrl("http://42.121.192.78:8086/ourangel-box-rpc/terminalSystem/updatePackage.html");
				rnt.setSign("c8db7d0e24e9a4ac3e42ec9c06ddc5f7");
				rnt.setParcelId(String.valueOf(parcel.getId()));
				rnt.setParcelNum(parcel.getParcelNum());
				rnt.setParcelStatus(3);
				rnt.setGetTime(parcel.getGetTime().toString());
				Thread thread = new Thread(rnt);
				thread.start();
			}
			response.put("result", "0");
		} else {
			response.put("result", "1");
		}
		return response;
	}
}
